package com.ymt.bpm.web.action.attach;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.service.platform.attach.AttachmentService;
import com.ymt.bpm.util.AES;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Johnny on 2017/4/18.
 */
@Controller
@RequestMapping(path="/view/platform/attach")
public class AttachController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Environment env;

    @Autowired
    private AttachmentService as;


    @RequestMapping(path="/preview/{attachmentIdEnc}")
    public ModelAndView preview(HttpServletRequest request,
                              @PathVariable("attachmentIdEnc")String attachmentIdEnc,
                              @RequestParam(value="v", required = false)String versionIdEnc,
                              @RequestParam("timezoneOffset")int timezoneOffset) {
        String[] profile = env.getActiveProfiles();
        String productionVersion = env.getProperty("bpmp.production-version", "0");
        String cdn = env.getProperty("bpmp.cdn", "/bpmp-resources");
        ModelAndView view = new ModelAndView("platform/attach/preview");
        view.addObject("profile", profile[0]);
        view.addObject("productionVersion", productionVersion);
        view.addObject("cdn", cdn);

        String attachmentId = AES.decrypt(attachmentIdEnc);
        String versionId = null;
        if (versionIdEnc!=null && versionIdEnc.length()>0) {
            versionId = AES.decrypt(versionIdEnc);
        }
        JSONObject previewObj = as.signaturePreview(attachmentId, versionId, timezoneOffset);
        view.addObject("name", previewObj.getString("name"));
        view.addObject("type", previewObj.getString("type"));
        view.addObject("previewUrl", previewObj.getString("previewUrl"));

        if ("url".equalsIgnoreCase(previewObj.getString("showType"))) {
            view.setViewName("redirect:" + previewObj.getString("previewUrl"));
        }

        return view;
    }

}
